import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import {getBackLoginToken, getBusinessLoginToken} from "@/api/login";

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  id: '',
  systemTime: 0,
  usCaSystemTime: 0,
  siteId: 'MX',
  platformNum: 1, // 对接的平台数量
  accountFalabella: false, // 是否对接了falabella平台
  accountShopee: false, // 是否对接了Shopee平台
  showMenuRemittance: false, // 菜单是否显示汇聚管理
  unbindAccountNum: 0, // 未绑定店铺数量
  localTime: '', // 通过接口获取当前站点的时间
  isShowLog:1,//是否显示日志

  usCaLocalTime: '',
  getNowTime: '',
  getUsCaNowTime: '',
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_IS_SHOW_LOG: (state, isShowLog) => {
    state.isShowLog = isShowLog
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_RECHARGE_CLOSE :(state,rechargeClose)=>{
    state.rechargeClose = rechargeClose
  },
  SET_USER_INFO :(state,userInfo)=>{
    state.userInfo = userInfo
  },
  SET_SYSTEM_TIME: (state,systemTime) => {
    state.systemTime = systemTime
  },
  SET_US_CA_SYSTEM_TIME: (state,usCaSystemTime) => {
    state.usCaSystemTime = usCaSystemTime
  },
  SET_SITE_ID: (state,siteId) => {
    state.siteId = siteId
  },

  SET_PLAT_NUM: (state,platformNum) => {
      state.platformNum = platformNum
    },
  SET_ACCOUNT_FALABELLA: (state,accountFalabella) => {
    state.accountFalabella = accountFalabella
  },
  SET_ACCOUNT_SHOPEE: (state,accountShopee) => {
    state.accountShopee = accountShopee
  },
  SET_INFO: (state,info) => {
    state.showMenuRemittance = info.showMenuRemittance
    state.unbindAccountNum = info.unbindAccountNum
    state.localTime = info.localTime
  },
  SET_US_CA_LOCAL_TIME: (state,usCaLocalTime) => {
    state.usCaLocalTime = usCaLocalTime
  },
  SET_GET_NOW_TIME: (state,getNowTime) => {
    state.getNowTime = getNowTime
  },
  SET_GET_US_CA_NOW_TIME: (state,getUsCaNowTime) => {
    state.getUsCaNowTime = getUsCaNowTime
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(res => {
        const { data, info } = res
        if(res.error === 0){
          commit('SET_TOKEN', info.token)
          setToken(info.token)
          resolve()
        }else{
          reject(res)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(res => {
        const { data, info } = res

        if (!data.id) {
          reject('Verification failed, please Login again.')
        }

        // const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        /*if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }*/

        // const roles = [data.accountType];
        // 用户角色
        const roles = ['admin']; // 卖家端不需要区分权限
        const name = data.account;
        const avatar = data.avatar;
        const introduction = '';

        commit('SET_ID', data.id)
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)

        commit('SET_IS_SHOW_LOG', info.isShowLog)


        commit('SET_SYSTEM_TIME', new Date(info.localTime).getTime())
        commit('SET_US_CA_SYSTEM_TIME', new Date(info.UsCaLocalTime).getTime())
        commit('SET_SITE_ID', data.siteId)
        commit('SET_PLAT_NUM', info.platformNum)
        commit('SET_ACCOUNT_FALABELLA', info.accountFalabella > 0)
        commit('SET_ACCOUNT_SHOPEE', info.accountShopee > 0)

        commit('SET_INFO', info)


        resolve({ roles, name, avatar, introduction })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  // 后台登录
  adminLogin({ commit } ,key){
    return new Promise((resolve, reject) =>{
      getBusinessLoginToken(key)
        .then( res => {
          const { info } = res
          if(res.error === 0){
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resetRouter()

            commit('SET_TOKEN', info.token)
            setToken(info.token)
            resolve()
          }else{
            reject(res)
          }
        }).catch( error => {
          reject(error)
        })
    })
  },

  // 更改时间
  setSystemTime({commit},time){
    commit('SET_SYSTEM_TIME',time)
  },
  setUsCaSystemTime({commit},time){
    commit('SET_US_CA_SYSTEM_TIME',time)
  },
  getNowTime({commit},time){
    commit('SET_GET_NOW_TIME',time)
  },
  getUsCaNowTime({commit},time){
    commit('SET_GET_US_CA_NOW_TIME',time)
  },
  // 演示登录
  backLogin({commit},key){
    return new Promise((resolve, reject) =>{
      getBackLoginToken(key)
        .then( res => {
          const { info } = res
          if(res.error === 0){
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resetRouter()

            commit('SET_TOKEN', info.token)
            setToken(info.token)
            resolve()
          }else{
            reject(res)
          }
        }).catch( error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
